package cn.itsource.service.impl;

import cn.itsource.domain.Account;
import cn.itsource.exception.NoAccountException;
import cn.itsource.exception.PasswordErrorException;
import cn.itsource.mapper.AccountMapper;
import cn.itsource.service.IAccountService;
import cn.itsource.utils.AccountContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private AccountMapper accountMapper;
    @Override
    public String getAccount(String userName,String password) {
        // 对从前端传送过来的数据进行判断
        if(userName.isBlank()){
            throw new RuntimeException("用户名必填！");
        }
        if(password.isBlank()){
            throw new RuntimeException("密码请填写！");
        }

        // 创建Account对象,如果不为空，那么说明数据库中有词条用户数据(数据校准)
        Account account = accountMapper.getUserByUserName(userName);
        if(account == null) {
            throw new NoAccountException("用户名不存在");
        }
        // 如果密码错误，说明用户名没问题，需要修改密码
        if(!password.equals(account.getPassword())) {
            throw new PasswordErrorException("密码错误");
        }
        // 生成一个token码
        String token = UUID.randomUUID().toString();
        // 将返回的正确账号储存到指定的集合中
        AccountContext.setAccountData(token, account);
        // 返回token
        return token;
    }
}
